/**
 * Copyright (c) 2008, Keisuke Inoue, Syracuse Unviersity
 * All rights reserved.
 *
 */
package edu.syr.iis.web.model;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import edu.syr.iis.web.util.HibernateUtil;

/**
 * @author kinoue
 *
 */
public class AdjacencyManager
{                
	/**
	 * Returns list of all Adjacency  sorted by AdjacencyId
	 */
	public List<Adjacency> getAdjacencies()
	{
		List<Adjacency> list = null;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		try
		{
			String query = "FROM Adjacency ORDER BY adjacencyId";
			list = session.createQuery(query).list();
			session.getTransaction().commit();
		}
		catch (HibernateException e)
		{
			session.getTransaction().rollback();
			throw e;
		}
		return list;
	}

	public Adjacency getAdjacency(int adjacencyId)
	{
		Adjacency adjacency = null;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		try 
		{
			adjacency = (Adjacency) session.get(Adjacency.class, adjacencyId);
		} 
		catch (HibernateException e)
		{
			session.getTransaction().rollback();
			throw e;
		}
		return adjacency;
	}

	public Adjacency getAdjacencyByLabel(String name)
	{
		Adjacency adjacency = null;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		Query query = session.createQuery("FROM Adjacency WHERE label = ?").setString(0, name);
		
		try 
		{			
			adjacency = (Adjacency) query.uniqueResult();
		} 
		catch (HibernateException e)
		{
			session.getTransaction().rollback();
			throw e;
		}
		return adjacency;
	}
		
	/**
	 * Saves a Adjacency object.
	 */
	public void saveAdjacency(Adjacency adjacency)
	{
		Session session = HibernateUtil.getSessionFactory()
		.getCurrentSession();
		session.beginTransaction();
		try
		{
			session.merge(adjacency);
			session.getTransaction().commit();
		}
		catch (HibernateException e)
		{
			session.getTransaction().rollback();
			throw e;
		}
	}

	/**
	 * Deletes Adjacency record with matching adjacencyId 
	 */
	public void deleteAdjacency(int adjacencyId)
	{
		Session session = 
			HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();	
		try
		{
			Object toDelete = session.get(Adjacency.class, new Integer(adjacencyId));

			if (toDelete != null) { 
				session.delete(toDelete);
			}

			session.flush();
			session.getTransaction().commit();
		}
		catch (HibernateException e)
		{
			session.getTransaction().rollback();
			throw e;
		}
	}


}
